#!/sbin/openrc-run

# Variables $user and $group are deprecated.
: ${command_user:="${user:-"nobody"}${group:+":$group"}"}
: ${python:="/usr/bin/python3"}
: ${python_opts:="-u"}  # this is needed for stdout/stderr redirect to work
: ${wsgi_module:=}
: ${wsgi_object:="application"}
: ${wsgi_call:="no"}

command="$python"
command_args="$python_opts /usr/bin/waitress-serve"
command_background="yes"

pidfile="/run/$RC_SVCNAME.pid"
start_stop_daemon_args="
	--interpreted
	--user $command_user
	${basedir:+--chdir $basedir}
	${start_stop_daemon_args:-}"

depends() {
	need net
	after postgresql
}

start_pre() {
	local waitress_args=""

	if [ "$RC_SVCNAME" = "waitress" ]; then
		ewarn "You are not supposed to run this runscript directly. Instead, you should"
		ewarn "create a symlink for the application you want to run as well as a copy of"
		ewarn "the configuration file and modify it appropriately, like so:"
		ewarn ""
		ewarn "    ln -s waitress /etc/init.d/myapp"
		ewarn "    cp /etc/conf.d/waitress /etc/conf.d/myapp"
		ewarn ""
	fi

	if [ -z "$wsgi_module" ]; then
		eerror '$wsgi_module must be set!'; return 1
	fi

	if [ -n "${logfile:-}" ]; then
		start_stop_daemon_args="$start_stop_daemon_args
			--stdout $logfile --stderr $logfile"
		checkpath -f -m 0644 -o ${command_user%:*} "$logfile"
	fi

	if [ -n "$unix_socket_path" ]; then
		if [ "$(stat -c %u "${unix_socket_path%/*}" 2>/dev/null)" -eq 0 ]; then
			eerror "Directory \"${unix_socket_path%/*}\" already exists and is owned by root!"
			return 1
		fi
		checkpath -d -m 0755 -o ${command_user%:*} "${unix_socket_path%/*}"
	fi

	if yesno "$wsgi_call"; then
		waitress_args="$waitress_args --call"
	fi

	local item; for item in ${listen_on:-}; do
		waitress_args="$waitress_args --listen='$item'"
	done

	waitress_args="$waitress_args
		$(optif --unix-socket "$unix_socket_path")
		$(optif --unix-socket-perms "$unix_socket_perms")
		$(optif --url-scheme "$url_scheme")
		$(optif --url-prefix "$url_prefix")
		$(optif --ident "$server_ident")
		${waitress_opts:-}
		$wsgi_module:$wsgi_object"

	command_args="$command_args $waitress_args"
}

optif() {
	test -n "$2" && printf %s "$1='$2'"
}
